import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/login/index.vue'
import Authorzie from '../views/authorize/index.vue'
import Auth from '../views/auth/index.vue'
import CallBack from '../views/callback/index.vue'
import Register from '@/views/register/index.vue'
import Forget from '@/views/forgot-password/index.vue'
import ResetPassword from '@/views/reset-password/index.vue'
import NProgress from './nprogress'
import { useUserStore } from '@/store/user'


const routes =[
  {
    path: '/login',
    component: Login,
    name: 'Login',
    meta: {
      title: 'Login',
      hidden: true,
    },
  },
  {
    path: '/register',
    component: Register,
    name: 'Register',
    meta: {
      title: 'Register',
      hidden: true,
    },

  },
  {
    path: '/authorize',
    component: Authorzie,
    name: 'Authorzie',
    meta: {
      title: 'Authorize',
      hidden: true,
    },
  },
  {
    path: '/auth',
    component: Auth,
    name: 'Auth',
    meta: {
      title: 'Auth',
      hidden: true,
    },
  },
  {
    path: '/forget',
    component: Forget,
    name: 'Forget',
    meta: {
      title: 'Forget',
      hidden: true,
    },
  },
  {
    path: '/reset-password',
    component: ResetPassword,
    name: 'ResetPassword',
    meta: {
      title: 'ResetPassword',
      hidden: true,
    },
  },
  {
    path: '/callback',
    component: CallBack,
    name: 'CallBack',
    meta: {
      title: 'CallBack',
      hidden: true,
    },
  },
]

// ========================
// 创建路由器实例
// ========================
const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PATH_PREFIX),
  routes,
})

 const whiteList = ['/login', '/register','/callback','/forget','/auth','/authorize','/reset-password']; // 白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  
  if (whiteList.includes(to.path.toLowerCase())) {
    // 如果在白名单中，直接放行
    return next();
  } 

  // 检查路由是否存在
  const matchedRoutes = router.resolve(to).matched;
  if (matchedRoutes.length === 0) {
    // 如果路由不存在，重定向到主页
    return next('/'); 
  }

  // 路由添加进去了没有及时更新 需要重新进去一次拦截
  if(!useUserStore().isAuthenticate){
    next("/authorize")
    return;
  }

  router.options.routes.forEach((item) => router.addRoute(item)) // 动态添加访问路由表

  next() // // 如果不传参数就会重新执行路由拦截，重新进到这里

});

router.afterEach(() => {
  NProgress.done();
});


export default router;